{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 文件添加前缀"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "\"\"\"\n",
    "在 Windows 下，您可以使用 Python 的 `os` 和 `os.path` 模块来对文件进行重命名并添加前缀。以下是一个示例代码，它可以遍历某个目录下的所有文件，并为每个文件添加指定的前缀：\n",
    "\n",
    "### 代码说明：\n",
    "1. **`os.listdir(directory)`**：列出目录中的所有文件和文件夹。\n",
    "2. **`os.path.isfile(old_file_path)`**：判断路径是否为文件，以防止误操作文件夹。\n",
    "3. **`os.rename(old_file_path, new_file_path)`**：对文件进行重命名。\n",
    "\n",
    "### 使用方法：\n",
    "1. 将 `directory` 替换为您的目标文件夹路径。\n",
    "2. 将 `prefix` 替换为您想要添加的前缀。\n",
    "3. 运行脚本即可自动为目录下的所有文件添加前缀并完成重命名。\n",
    "\"\"\"\n",
    "\n",
    "import os\n",
    "\n",
    "def add_prefix_to_files(directory, prefix):\n",
    "    # 遍历目录下的所有文件\n",
    "    for filename in os.listdir(directory):\n",
    "        # 构建完整的文件路径\n",
    "        old_file_path = os.path.join(directory, filename)\n",
    "        \n",
    "        # 检查是否是文件，防止操作到文件夹\n",
    "        if os.path.isfile(old_file_path):\n",
    "            # 构建新的文件名和路径\n",
    "            new_filename = prefix + filename\n",
    "            new_file_path = os.path.join(directory, new_filename)\n",
    "            \n",
    "            # 重命名文件\n",
    "            os.rename(old_file_path, new_file_path)\n",
    "            # print(f\"Renamed: {old_file_path} to {new_file_path}\")\n",
    "\n",
    "# 使用示例\n",
    "directory = \"\"  # 替换为你的目标目录\n",
    "prefix = \"\"  # 替换为你想添加的前缀\n",
    "\n",
    "add_prefix_to_files(directory, prefix)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 文件重命名"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "  \n",
    "def replace_filename_part(root_dir, old_part, new_part):  \n",
    "    \"\"\"  \n",
    "    遍历指定目录及其子目录，将文件名中包含old_part的部分替换为new_part。  \n",
    "      \n",
    "    :param root_dir: 要遍历的根目录  \n",
    "    :param old_part: 文件名中要替换的旧部分  \n",
    "    :param new_part: 替换后的新部分  \n",
    "    \"\"\"  \n",
    "    for root, dirs, files in os.walk(root_dir):  \n",
    "        for file in files:  \n",
    "            if old_part in file:  \n",
    "                # 构建原文件完整路径  \n",
    "                old_file_path = os.path.join(root, file)  \n",
    "                # 替换文件名中的部分并构建新文件完整路径  \n",
    "                new_file_name = file.replace(old_part, new_part)  \n",
    "                new_file_path = os.path.join(root, new_file_name)  \n",
    "                # 重命名文件  \n",
    "                os.rename(old_file_path, new_file_path)  \n",
    "                # print(f\"Renamed '{old_file_path}' to '{new_file_path}'\")  \n",
    "  \n",
    "# 指定要遍历的根目录  \n",
    "root_directory = ''  \n",
    "# 调用函数，替换文件名  \n",
    "replace_filename_part(root_directory, '', '')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 根据关键字添加前缀"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "import os\n",
    "\n",
    "# 设置文件夹路径\n",
    "folder_path = \"\"\n",
    "# 输入前缀列表和关键字符串列表\n",
    "append_str_list = ['']\n",
    "key_str_list = [\"\"]\n",
    "\n",
    "if not os.path.exists(folder_path):\n",
    "    print(f\"路径 '{folder_path}' 不存在，请检查后重试。\")\n",
    "else:\n",
    "    if len(append_str_list) != len(key_str_list):\n",
    "        print(\"前缀列表和关键字符串列表的长度不匹配，请重新输入。\")\n",
    "    else:\n",
    "        # 遍历文件夹下的所有文件和子文件夹\n",
    "        for root, dirs, files in os.walk(folder_path):\n",
    "            for file in files:\n",
    "                # 针对每个关键字符串和对应的前缀进行检查和处理\n",
    "                for append_str, key_str in zip(append_str_list, key_str_list):\n",
    "                    # 检查文件名是否包含关键字符串，并且不是以前缀开头\n",
    "                    if key_str in file and not file.startswith(append_str):\n",
    "                        old_file_path = os.path.join(root, file)\n",
    "                        new_file_name = append_str + file\n",
    "                        new_file_path = os.path.join(root, new_file_name)\n",
    "\n",
    "                        # 检查新文件名是否已存在\n",
    "                        if os.path.exists(new_file_path):\n",
    "                            print(f'警告：文件 \"{new_file_path}\" 已存在，跳过重命名。')\n",
    "                        else:\n",
    "                            try:\n",
    "                                # 重命名文件\n",
    "                                os.rename(old_file_path, new_file_path)\n",
    "                                # print(f'Renamed \"{old_file_path}\" to \"{new_file_path}\"')\n",
    "                            except Exception as e:\n",
    "                                print(f'Error renaming \"{old_file_path}\": {e}')\n",
    "\n",
    "        print(\"文件重命名完成。\")\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 获取所有文件的名称"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import math\n",
    "from moviepy import *\n",
    "import sys\n",
    "\n",
    "# 指定目标目录列表\n",
    "# directories = ['']\n",
    "directories = ['']\n",
    "\n",
    "# 定义一个函数，用于将文件大小转换为合适的单位（GB, MB, KB）\n",
    "def convert_size(size_bytes):\n",
    "    if size_bytes == 0:\n",
    "        return \"0B\"\n",
    "    size_name = (\"B\", \"KB\", \"MB\", \"GB\", \"TB\", \"PB\", \"EB\", \"ZB\", \"YB\")\n",
    "    i = int(math.floor(math.log(size_bytes, 1024)))\n",
    "    p = math.pow(1024, i)\n",
    "    s = round(size_bytes / p, 2)\n",
    "    return f\"{s} {size_name[i]}\"\n",
    "\n",
    "# 定义一个函数，用于获取视频时长\n",
    "def get_video_duration(file_path):\n",
    "    try:\n",
    "        with VideoFileClip(file_path) as video:\n",
    "            duration = video.duration\n",
    "        return round(duration, 2)  # 返回时长，保留两位小数\n",
    "    except Exception as e:\n",
    "        print(f\"Error getting duration for {file_path}: {e}\")\n",
    "        return None\n",
    "\n",
    "# 定义一个函数，用于将秒数转换为 xxhxxmin 格式\n",
    "def format_duration(seconds):\n",
    "    if seconds is None:\n",
    "        return \"N/A\"\n",
    "    hours = int(seconds // 3600)\n",
    "    minutes = int((seconds % 3600) // 60)\n",
    "    seconds_remaining = int(seconds % 60)\n",
    "    duration_str = \"\"\n",
    "    if hours > 0:\n",
    "        duration_str += f\"{hours}h\"\n",
    "    if minutes > 0:\n",
    "        duration_str += f\"{minutes}min\"\n",
    "    if seconds_remaining > 0 and not duration_str:  # 如果没有小时和分钟，显示秒\n",
    "        duration_str += f\"{seconds_remaining}s\"\n",
    "    return duration_str\n",
    "\n",
    "# 创建一个列表来存储文件信息\n",
    "files_info = []\n",
    "\n",
    "# 遍历目录列表\n",
    "for directory in directories:\n",
    "    # 获取目录下所有文件和文件夹的名称\n",
    "    all_files = os.listdir(directory)\n",
    "    # 过滤掉文件夹，仅保留文件\n",
    "    for f in all_files:\n",
    "        file_path = os.path.join(directory, f)\n",
    "        if os.path.isfile(file_path):\n",
    "            # 提取年份\n",
    "            year = f[:4]\n",
    "            # 获取文件大小\n",
    "            file_size_bytes = os.path.getsize(file_path)\n",
    "            # 转换文件大小为合适的单位\n",
    "            file_size = convert_size(file_size_bytes)\n",
    "            # 获取视频时长（秒）\n",
    "            video_duration_seconds = get_video_duration(file_path)\n",
    "            # 格式化视频时长为 xxhxxmin\n",
    "            video_duration = format_duration(video_duration_seconds)\n",
    "            # 将文件信息添加到列表中\n",
    "            files_info.append((year, f, file_size, video_duration, directory))\n",
    "\n",
    "# 按照年份和文件名称排序\n",
    "files_info.sort(key=lambda x: (x[0], x[1]))\n",
    "\n",
    "# 打印序号、年份、文件名、文件大小、视频时长、文件所属位置\n",
    "for index, (year, file_name, file_size, video_duration, file_location) in enumerate(files_info, start=1):\n",
    "    print(f\"{file_name}\\t{video_duration}\\t{file_size}\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 根据文件夹名称给文件添加前缀"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "current_dir = ''\n",
    "\n",
    "for entry in os.scandir(current_dir):\n",
    "    if entry.is_dir():\n",
    "        folder_name = entry.name\n",
    "        prefix = f'【{folder_name}】'\n",
    "        # 遍历子文件夹中的所有文件（包括子目录中的文件）\n",
    "        for root, dirs, files in os.walk(entry.path):\n",
    "            for filename in files:\n",
    "                if filename.startswith(prefix):\n",
    "                    print(f\"文件 '{filename}' 已包含前缀，跳过\")\n",
    "                    continue\n",
    "                new_name = prefix + filename\n",
    "                original_path = os.path.join(root, filename)\n",
    "                new_path = os.path.join(root, new_name)\n",
    "                # 检查新文件名是否存在\n",
    "                if os.path.exists(new_path):\n",
    "                    print(f\"警告：文件 '{new_name}' 已存在，跳过重命名\")\n",
    "                    continue\n",
    "                try:\n",
    "                    os.rename(original_path, new_path)\n",
    "                    print(f\"已将 '{filename}' 重命名为 '{new_name}'\")\n",
    "                except Exception as e:\n",
    "                    print(f\"重命名 '{filename}' 失败：{str(e)}\")"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "torch",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
